using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;
using ImageProcessing.Utility;

namespace ImageReview
{
    public partial class PreviewRow : System.Web.UI.UserControl
    {
        // This is the complete image set object that this row belongs to.
        private TPDSControl.ImageSet _imageset;
        public TPDSControl.ImageSet ImageSet
        {
            get
            {
                if (_imageset == null)
                {
                    _imageset = new TPDSControl.ImageSet();
                }
                return _imageset;
            }
            set
            {
                _imageset = value;
            }
        }

        // This is the list of images this row contains.
        private List<TPDSControl.Image> _rowImages = new List<TPDSControl.Image>( );
        public List<TPDSControl.Image> RowImages
        {
            get { return _rowImages; }
        }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["ConsignmentNumberReadonly"] == null)
                Session["ConsignmentNumberReadonly"] = false;
            
            if (Session["GoodsIDReadonly"] == null)
                Session["GoodsIDReadonly"] = false;

            if (Session["CurrentPage"] == null)
                Session["CurrentPage"] = CurrentPage.Review;

            if (Session["CurrentUsername"] == null)
            {
                string username = this.Page.User.Identity.Name;
                username = username.Substring(username.LastIndexOf('\\') + 1);
                Session["CurrentUsername"] = username;
            }

            //load PreviewItem controls into the PreviewItems placeholder
            PlaceHolder PreviewBarcodeHolder = (PlaceHolder)this.FindControl("PreviewBarcode");
            PlaceHolder PreviewRowsHolder = (PlaceHolder)this.FindControl("PreviewItems");
            AddPreviewItems(ImageSet, PreviewRowsHolder, PreviewBarcodeHolder);

            TextBox ConsignmentNo = (TextBox)this.FindControl("ConsignmentNo");
            TextBox GoodsID = (TextBox)this.FindControl("GoodsID");
            PlaceHolder PreviewAcceptHolder = (PlaceHolder)this.FindControl("PreviewAccept");

            if ((CurrentPage)Session["CurrentPage"] == CurrentPage.Review)
            {
                //add the Accept Images linkbutton into the PreviewAccept placeholder
                LinkButton lnkAccept = new LinkButton();
                lnkAccept.Text = "Accept Images";
                lnkAccept.Click += new EventHandler(lnkAccept_Click);
                lnkAccept.OnClientClick = "javascript:return validate('" + ConsignmentNo.ClientID + "','" + GoodsID.ClientID + "')";
                lnkAccept.CssClass = "barcodelabels";
                lnkAccept.ID = "Accept";

                PreviewAcceptHolder.Controls.Add(lnkAccept);
            }
            else if ((CurrentPage)Session["CurrentPage"] == CurrentPage.Accept)
            {
                //add the Delete Set linkbutton into the PreviewAccept placeholder
                LinkButton lnkDeleteSet = new LinkButton();
                lnkDeleteSet.Text = "Delete Set";
                lnkDeleteSet.Click += new EventHandler(lnkDeleteSet_Click);
                lnkDeleteSet.CssClass = "barcodelabels";
                PreviewAcceptHolder.Controls.Add(lnkDeleteSet);

                PreviewAcceptHolder.Controls.Add(new HtmlGenericControl("BR"));

                //add the Send back for review linkbutton into the PreviewAccept placeholder
                LinkButton lnkReview = new LinkButton();
                lnkReview.Text = "Review";
                lnkReview.Click += new EventHandler(lnkReview_Click);
                lnkReview.CssClass = "barcodelabels";
                PreviewAcceptHolder.Controls.Add(lnkReview);
            }

            Label lblNotFound = new Label();
            lblNotFound.ID = "lblNotFound";
            lblNotFound.Text = "Not found";
            lblNotFound.CssClass = "deletelabels";
            lblNotFound.Visible = false;
            PlaceHolder phNotFound = (PlaceHolder)this.FindControl("phNotFound");
            phNotFound.Controls.Add(lblNotFound);

            if (Convert.ToBoolean(Session["ConsignmentNumberReadonly"]))
            {
                ConsignmentNo = (TextBox)this.FindControl("ConsignmentNo");
                ConsignmentNo.ReadOnly = true;
                ConsignmentNo.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
                ConsignmentNo.BorderStyle = BorderStyle.None;
            }

            if (Convert.ToBoolean(Session["GoodsIDReadonly"]))
            {
                GoodsID = (TextBox)this.FindControl("GoodsID");
                GoodsID.ReadOnly = true;
                GoodsID.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
                GoodsID.BorderStyle = BorderStyle.None;
            }
        }

        private void AddPreviewItems(TPDSControl.ImageSet imageset, PlaceHolder previewItemsHolder, PlaceHolder barcodeItemHolder)
        {
            // Add item for each image object we have
            foreach( TPDSControl.Image image in this.RowImages )
            {
                // Create PreviewItem object.
                PreviewItem previewItem = (PreviewItem)LoadControl("PreviewItem.ascx");
                previewItem.Image = image;

                // Assign the item to the holder based on whether a barcode or not.
                if (image.IsBarcode)
                {
                    previewItem.IsBarCodeImage = true;
                    barcodeItemHolder.Controls.Add(previewItem);

                    GoodsID.Text = image.BarcodeNo;
                    ConsignmentNo.Text = image.ConsignmentNo;
                }
                else
                    previewItemsHolder.Controls.Add(previewItem);
            }
        }
        private string GetNextSuffix(string currentSuffix)
        {
            if (currentSuffix.Length != 2)
                throw new Exception("Incorrect Suffix format.");
            char char1 = currentSuffix[0];
            char char2 = currentSuffix[1];

            if (char2 == 'z')
            {
                char1++;
                char2 = 'a';
                return String.Concat(char1, char2);
            }
            char2++;

            return string.Concat(char1, char2);
        }
        void lnkAccept_Click(object sender, EventArgs e)
        {
            TextBox GoodsID = (TextBox)this.FindControl("GoodsID");
            TextBox ConsignmentNo = (TextBox)this.FindControl("ConsignmentNo");

            // Retrieve configuration xml file.
            TPDSConfig.TPDSConfig ConfigFile = TPDSWEBConfig.Load( Server.MapPath( @"~/" ) );
            if( ConfigFile == null )
                return;

            string suffix = "aa";

            try
            {
                if( GoodsID.Text.Trim( ).Equals( string.Empty ) )
                {
                    foreach( TPDSControl.Image image in RowImages )
                    {
                        image.ConsignmentNo = ConsignmentNo.Text;
                        image.IsWaiting = true;
                        image.GenerateNewFilename( Server.MapPath( @"~/" ), suffix );
                        suffix = GetNextSuffix(suffix);
                    }
                    _imageset.Save( );
                }
                else
                {
                    List<string> existingFiles = new List<string>();
                    foreach (TPDSControl.Image image in RowImages)
                    {
                        string oldExtention = Path.GetExtension(image.Filename);
                        string newFilename = String.Empty;
                        if (!image.IsBarcode)
                        {
                            newFilename = GoodsID.Text + suffix + oldExtention;
                            suffix = GetNextSuffix(suffix);
                            string destinationFolder = Path.Combine(ConfigFile.DestinationFolder, Session["CurrentUsername"].ToString());
                            if (File.Exists(Path.Combine(destinationFolder, newFilename)))
                            {
                                string imagename = image.Filename.Substring(image.Filename.LastIndexOf("\\"));
                                existingFiles.Add(imagename);
                            }
                        }
                    }
                    System.Web.UI.WebControls.Literal control = (Literal)((_Default)this.Page).FindControl("literalMessage");

                    if (existingFiles.Count > 0)
                    {
                        string output = string.Empty;
                        foreach (string files in existingFiles)
                        {
                            output += files + "\n";
                        }
                        control.Text = string.Format("The following Images with the target Good ID already exist in OUTPUT_IMAGES folder.<Br/>{0}<br/>You can go to Process page to process the image or delete the images first and then continue here.');</script>", output);
                        control.Visible = true;
                        return;
                    }
                    else
                    {
                        control.Text = string.Empty;
                        control.Visible = false;
                    }
                    suffix = "aa";

                    foreach( TPDSControl.Image image in RowImages )
                    {
                        string oldExtention = Path.GetExtension( image.Filename );
                        string newFilename = String.Empty;
                        if( !image.IsBarcode )
                        {
                            newFilename = GoodsID.Text + suffix + oldExtention;
                            suffix = GetNextSuffix(suffix);
                            string destinationFolder = Path.Combine( ConfigFile.DestinationFolder,Session["CurrentUsername"].ToString());
                            if (!Directory.Exists(destinationFolder))
                            {
                                Directory.CreateDirectory(destinationFolder);
                            }
                            image.Move(Server.MapPath(@"~/"), Path.Combine(destinationFolder, newFilename));

                            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(Path.Combine(destinationFolder, newFilename));
                            ImageExt originalImg = new ImageExt(originalImage);
                            string thumbFolder = Path.Combine(destinationFolder, "thumb");
                            if(!Directory.Exists(thumbFolder))
                            {
                                Directory.CreateDirectory(thumbFolder);
                            }
                            originalImg.Resize(4, 3, 132).SaveJpeg(Path.Combine(thumbFolder, newFilename));
                            originalImg.Dispose();
                            originalImage.Dispose();
                        }
                        else
                        {
                            image.Delete( Server.MapPath( @"~/" ) );
                        }

                        image.DeleteFromImageset( );
                    }
                }

                // Flag that the page contents have changed and we must reload
                ( (_Default)this.Page ).RequiresReload = true;

                //Response.Redirect(Request.Url.ToString(), false);
            }
            catch (Exception ex)
            {
                Response.Write("<script type=\"text/javascript\">alert('" + ex.Message.Replace("'", "").Replace(@"\", @"\\") + "');</script>");
            }
        }

        private void lnkDeleteSet_Click(object sender, EventArgs e)
        {
            // Retrieve configuration xml file.
            TPDSConfig.TPDSConfig ConfigFile = TPDSWEBConfig.Load( Server.MapPath( @"~/" ) );
            if( ConfigFile == null )
                return;

            try
            {
                foreach (TPDSControl.Image image in RowImages)
                {
                    image.Delete(Server.MapPath(@"~/"));
                    image.DeleteFromImageset();
                }                
                Response.Redirect("Accept.aspx", true);
            }
            catch (Exception ex)
            {
                Response.Write("<script type=\"text/javascript\">alert('" + ex.Message.Replace("'", "").Replace(@"\", @"\\") + "');</script>");
            }
        }

        private void lnkReview_Click(object sender, EventArgs e)
        {
            // Retrieve configuration xml file.
            TPDSConfig.TPDSConfig ConfigFile = TPDSWEBConfig.Load( Server.MapPath( @"~/" ) );
            if( ConfigFile == null )
                return;

            try
            {
                foreach (TPDSControl.Image image in RowImages)
                {
                    if (image.IsWaiting)
                        image.IsWaiting = false;
                }
                _imageset.Save();
                Response.Redirect("Default.aspx", true);
            }
            catch (Exception ex)
            {
                Response.Write("<script type=\"text/javascript\">alert('" + ex.Message.Replace("'", "").Replace(@"\", @"\\") + "');</script>");
            }
        }
    }
}